-module(ifriend_worker).
-behaviour(gen_server).
-include("../include/records.hrl").

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).


-record(ifriendWorkerState,{id,fom,followedList,followerList}).

%%====================================================================
%% gen_server callbacks
%%====================================================================
%%    {ok, MetaWorkerPid}=gen_server:start({local,ProcessName}, meta_worker, [FileRecord, write,UserName], []),
init([ID]) ->
	process_flag(trap_exit,true),
	error_logger:info_msg("[~p, ~p]: start ifriendworker ~p~n", [?MODULE, ?LINE, ID]),    
	case ifriend_db:select_from_account_byid(ID) of
		[Acc]->
			
			case ifriend_db:select_from_frame_byid(ID) of
				[{Fom,Fid}]->
					get;
				[]->
					default
			end,
					
			
			State=#ifriendWorkerState{id=ID,followedList = Acc#account.followedlist,followerList = Acc#account.followerlist},
			{ok, State};
		[]->
			{ok, []}
	end.

%% ===============================================================================================================
%%ifriend 实现的 operation 接口
%%1 synchronize 联系人 （进程序默认不synchronize了）。
%%	如果联系人内容修改，也要更新。md5码确认。
%%	本地计算md5，如果没变化就不用服务器确认就更新完
%%2 auto ->synchronize status	（进程序默认开始，有提示更新，不自动更新）
%%	进程序就更新很慢的话，可以用缓存和提示
%%	不过这样就不能知道新回复数了，还是用简单粗暴的吧，直接读一遍。。。
%%3 reply to
%%
%%4 update my status
%%	
%%5 auto->prompt 
%%	延迟更新。 定时更新 

%% =============================================================   interface . =========================================
handle_call({update_status,ID,NewS},_From,State)->
	case ifriend_db:back_up_old_frame(ID) of
		ok->
			case ifriend_db:add_notification(State#ifriendWorkerState.followerList) of
				ok->
					erlang,
					ok;
				{error,Why}->
					Why
			end;
		{error,WHY}->
			{reply,{error,WHY},State}
	end;
	
	
  
handle_call({queryAllfollowd},_From,State)->
	ifriend_common:queryAllFollowedFunc(State#ifriendWorkerState.id);



handle_call({debug},{_From, _},State)->    
    error_logger:info_msg(" someone is checking my state.~n"),
    {reply,{self(),State},State}.


handle_cast(_Msg, State) ->    
    {noreply, State}.

handle_info({'EXIT', _Pid, Why}, State) ->   %%
     error_logger:info_msg("[~p, ~p]: EXiT. Why: ~p~n",[?MODULE, ?LINE,Why]),     
     NewState = State#ifriendWorkerState{},
	 {stop,"test",NewState};  %%% {noreply,State,timeout}  |{noreply,State}
	

handle_info(_Info, State) ->
%%     error_logger:info_msg("handle_info.~n"),
    {noreply, State}.

terminate(Reason, _State) ->
 	error_logger:info_msg("[~p, ~p]: close metaworker ~p since ~p~n", [?MODULE, ?LINE, self(),Reason]),	
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


